package com.creditease.mobile.news.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.os.AsyncTask;
import android.widget.ImageView;
import com.creditease.mobile.util.FileUtil;
import com.creditease.mobile.util.HttpUtils;
import com.creditease.mobile.util.LruCacheUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class BitmapWorkerTask extends AsyncTask {
    private ImageView gView;

    @Override
    protected Object doInBackground(Object... params) {
        String url = (String) params[0];
        String filePath = (String) params[1];
        ImageView pic = (ImageView) params[2];
        this.gView = pic;
        try {
            File file = new File(filePath);
            if (file.exists()) {
                Bitmap bmp = BitmapFactory.decodeFile(filePath);
                return decodeFil(url, bmp);
            } else {
                Drawable drawable = loadImageFromUrl(url);
                BitmapDrawable bd = (BitmapDrawable) drawable;
                if (bd != null) {
                    Bitmap bmp = bd.getBitmap();
                    FileOutputStream fos = new FileOutputStream(filePath);
                    bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
                    fos.flush();
                    fos.close();
                    return decodeFil(url, bmp);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private Object decodeFil(String url, Bitmap bmp) {
        Bitmap resizeBitmap = ThumbnailUtils.extractThumbnail(bmp, 80, 60, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        LruCacheUtil.addBitmapToCache(url, resizeBitmap);
        return resizeBitmap;
    }

    // 从网络上取数据方法 new URL(imageUrl).openStream()
    protected Drawable loadImageFromUrl(String imageUrl) throws IOException {
        try {
            // 测试时，模拟网络延时，实际时这行代码不能有
            // SystemClock.sleep(2000);
            InputStream is = HttpUtils.getHttpStream(imageUrl);
            if (is != null) {
                String fileName = FileUtil.getFileName(imageUrl);
                return Drawable.createFromStream(is, fileName);
            }
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    protected void onPostExecute(Object o) {
        if (o != null) {
            gView.setImageBitmap((Bitmap) o);
        }
        super.onPostExecute(o);
    }
}